//
//  LSMeassgeCenterViewController.m
//  LaSaCivilAffairsDepartment
//
//  Created by 聂志康 on 2019/8/23.
//  Copyright © 2019 wpkj. All rights reserved.
//

#import "LSMeassgeCenterViewController.h"
#import "LSLevinBookListViewCell.h"
#import "LSMeassgeCenterListModel.h"
#import "LSYueBanInfoVC.h"//阅办详情
#import "LSNiWenInfoVC.h"//拟文详情
#import "LSAttendanceRecordsDetailViewController.h"//OA部分详情

#define headerSearchViewHeight 50
#define rows 10

@interface LSMeassgeCenterViewController () <UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArrayM;
@property (nonatomic, strong) UITextField *selectTF;
@property (nonatomic, assign) int page;
@property (nonatomic, strong) NZKNoDataView *nodataView;
@property (nonatomic, strong) NZKNetworkErrorView *networkErrorView;
@property (nonatomic, strong) NSArray *dataArray;
@end

static NSString *LSLevinBookListViewCellID = @"LSLevinBookListViewCellID";

@implementation LSMeassgeCenterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"消息列表";
    [self addHeaderSearchView];
    [self.view addSubview:self.tableView];
    [self loadData];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
}

- (void)addHeaderSearchView {
    UIView *headerSelectView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, headerSearchViewHeight)];
    headerSelectView.backgroundColor = UIColor.whiteColor;
    headerSelectView.layer.shadowRadius = 5;
    headerSelectView.layer.shadowColor = hexColor(cccccc).CGColor;
    
    UITextField *selectTF = [[UITextField alloc] initWithFrame:CGRectMake(12, 12, ScreenWidth-(headerSearchViewHeight-8)-12-12-12, 50-4-12)];
    selectTF.layer.borderColor = hexColor(dddddd).CGColor;
    selectTF.layer.borderWidth = 1;
    self.selectTF = selectTF;
    selectTF.delegate = self;
    selectTF.placeholder = @"请输入标题";
    selectTF.font = [UIFont systemFontOfSize:15];
    UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 1)];
    selectTF.leftView = leftView;
    selectTF.leftViewMode = UITextFieldViewModeAlways;
    [headerSelectView addSubview:selectTF];
    
    UIButton *searchButton = [[UIButton alloc] initWithFrame:CGRectMake(ScreenWidth-12-50, 12, 50, headerSearchViewHeight-4-12)];
    searchButton.backgroundColor = NAV_COLOR;
    searchButton.layer.cornerRadius = 5;
    searchButton.layer.masksToBounds = true;
    [searchButton setTitle:@"搜索" forState:UIControlStateNormal];
    [searchButton setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    searchButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [searchButton addTarget:self action:@selector(loadData) forControlEvents:UIControlEventTouchUpInside];
    [headerSelectView addSubview:searchButton];
    
    [self.view addSubview:headerSelectView];
}

- (void)loadData {
    self.page = 1;
    //,@"username":[UserInfoModel sharedInstance].customerNickname
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:true];
    NSDictionary *param = @{@"token":[UserInfoModel sharedInstance].token,
                            @"page":[NSString stringWithFormat:@"%d",self.page],
                            @"rows":[NSString stringWithFormat:@"%d",rows],
                            @"title":self.selectTF.text
                  };
    [NetworkUtils requestNOHandleWithMethod:@"GET" URL:xxtxListForApp param:param completionHandler:^(id responseObject, NSError *connectionError) {
        [hud hideAnimated:true];
        if (!connectionError) {
            NSNumber *status = [responseObject objectForKey:@"status"];
            if (status.integerValue == 200) {
                self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
                [self.tableView.mj_header endRefreshing];
                NSArray *dataArray = [responseObject objectForKey:@"data"];
                if (dataArray && dataArray.count > 0) {
                    [self.dataArrayM removeAllObjects];
                    [self.nodataView removeFromSuperview];
                    [self.networkErrorView removeFromSuperview];
                    for (NSDictionary *dict in dataArray) {
                        LSMeassgeCenterListModel *model = [LSMeassgeCenterListModel meassgeCenterListModelWithDict:dict];
                        if (model) {
                            [self.dataArrayM addObject:model];
                        }
                    }
                    if (self.dataArrayM.count < self.page*rows) {
                        [self.tableView.mj_footer endRefreshingWithNoMoreData];
                    }
                } else {
                    [self.networkErrorView removeFromSuperview];
                    [self.tableView addSubview:self.nodataView];
                }
                [self.tableView reloadData];
            } else {
                [self.nodataView removeFromSuperview];
                [self.tableView addSubview:self.networkErrorView];
                self.networkErrorView.tipText = [ValidateUtils validateNull:responseObject[@"message"]];
            }
        } else {
            [self.nodataView removeFromSuperview];
            [self.tableView addSubview:self.networkErrorView];
            self.networkErrorView.tipText = [NSString stringWithFormat:@"%@",connectionError.localizedDescription];
        }
    }];
}

- (void)loadMoreData {
    self.page++;
    //, @"username":[UserInfoModel sharedInstance].customerNickname
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:true];
    NSDictionary *param = @{@"token":[UserInfoModel sharedInstance].token,
                            @"page":[NSString stringWithFormat:@"%d",self.page],
                            @"rows":[NSString stringWithFormat:@"%d",rows],
                            @"title":self.selectTF.text
                  };
    [NetworkUtils requestNOHandleWithMethod:@"POST" URL:xxtxListForApp param:param completionHandler:^(id responseObject, NSError *connectionError) {
        [hud hideAnimated:true];
        if (!connectionError) {
            NSNumber *status = [responseObject objectForKey:@"status"];
            NSNumber *totalCount = responseObject[@"totalNum"];
            if (status.integerValue == 200) {
                NSArray *dataArray = [responseObject objectForKey:@"data"];
                if (dataArray > 0) {
                    for (NSDictionary *dict in dataArray) {
                        LSMeassgeCenterListModel *model = [LSMeassgeCenterListModel meassgeCenterListModelWithDict:dict];
                        if (model) {
                            [self.dataArrayM addObject:model];
                        }
                    }
                    if (totalCount.intValue < rows) {
                        [self.tableView.mj_footer endRefreshingWithNoMoreData];
                    } else {
                        [self.tableView.mj_footer endRefreshing];
                    }
                    [self.tableView reloadData];
                }
            } else {
                self.page--;
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }
        } else {
            self.page--;
            [self.tableView.mj_footer endRefreshing];
            [MBProgressHUD showTipMessageInWindow:connectionError.localizedDescription];
        }
    }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataArrayM.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    LSLevinBookListViewCell *cell = [tableView dequeueReusableCellWithIdentifier:LSLevinBookListViewCellID forIndexPath:indexPath];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    cell.centerListModel = self.dataArrayM[indexPath.section];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:true];
    LSMeassgeCenterListModel *centerListModel = self.dataArrayM[indexPath.section];
    NSDictionary *param = @{@"token":[UserInfoModel sharedInstance].token,@"id":centerListModel.ID};
    [NetworkUtils requestNOHandleWithMethod:@"POST" URL:xxtxxqForApp param:param completionHandler:^(id responseObject, NSError *connectionError) {
        if (!connectionError) {
            NSNumber *status = [responseObject objectForKey:@"status"];
            if (status.integerValue == 200) {
                centerListModel.state = [NSNumber numberWithInt:1];
                [self.tableView reloadData];
            } else {
                [MBProgressHUD showTipMessageInWindow:[responseObject objectForKey:@"message"]];
            }
        } else {
            [MBProgressHUD showTipMessageInWindow:connectionError.localizedDescription];
        }
    }];
    if ([centerListModel.tableName isEqualToString:@"t_b_file_review"]) {
        LSYueBanInfoVC *lvc = [[LSYueBanInfoVC alloc]init];
        lvc.type = 1;
        lvc.isFromMessageCenter = true;
        NSDictionary *dict = @{@"id":centerListModel.tableId,@"bpmStatus":centerListModel.state};
        lvc.dict = dict;
        [self .navigationController pushViewController:lvc animated:YES];
    } else if ([centerListModel.tableName isEqualToString:@"lf_send_file"]) {
        LSNiWenInfoVC *lvc = [[LSNiWenInfoVC alloc]init];
        lvc.type = 1;
        NSDictionary *dict = @{@"id":centerListModel.tableId,@"bpmStatus":centerListModel.state};
        lvc.dict = dict;
        [self.navigationController pushViewController:lvc animated:YES];
    } else if ([centerListModel.tableName isEqualToString:@"lf_approve"]) {
        [NetworkUtils requestNOHandleWithMethod:@"POST" URL:findTypeByTableId param:@{@"token":[UserInfoModel sharedInstance].token,@"tableId":centerListModel.tableId} completionHandler:^(id responseObject, NSError *connectionError) {
            if (!connectionError) {
                NSNumber *status = [responseObject objectForKey:@"status"];
                if (status.integerValue == 200) {
                    NSArray *dataArray = [responseObject objectForKey:@"data"];
                    if (dataArray && dataArray.count > 0) {
                        NSDictionary *dataDict = dataArray.firstObject;
                        NSString *approveType = dataDict[@"approveType"];
                        [self jumpDetailViewControllerWithApproveType:approveType.integerValue andModel:centerListModel];
                    } else {
                        [MBProgressHUD showTipMessageInWindow:[ValidateUtils validateNull:responseObject[@"message"]]];
                    }
                } else {
                    [MBProgressHUD showTipMessageInWindow:[ValidateUtils validateNull:responseObject[@"message"]]];
                }
            } else {
                [MBProgressHUD showTipMessageInWindow:[NSString stringWithFormat:@"%@",connectionError.localizedDescription]];
            }
        }];
    }
}

- (void)jumpDetailViewControllerWithApproveType:(NSInteger)approveType andModel:(LSMeassgeCenterListModel *)model {
    LSAttendanceRecordsDetailViewController *attendanceRecordsDC = [[LSAttendanceRecordsDetailViewController alloc] init];
    attendanceRecordsDC.fromVC = @"消息中心";
    attendanceRecordsDC.listID = [ValidateUtils validateNull:model.tableId];
    attendanceRecordsDC.approveType = approveType;
    attendanceRecordsDC.approveState = model.state.integerValue;
    switch (approveType) {
        case 1:
        {
            attendanceRecordsDC.tipTitleLabelArray = @[@"请假事由：",@"姓名：",@"职务：",@"科室：",@"请假类型：",@"请假时长：",@"时间：",@"抄送：",@"审批人：",@"审批状态："];
            attendanceRecordsDC.infoTitleLabelArray = @[@"APPROVE_MAIN",@"CREATE_NAME",@"TYPENAME",@"SYS_ORG_CODE",@"LEAVE_TYPE",@"LEAVE_DURATION",@"BETWEEN_TIME",@"SEND_NAME",@"APPROVE_NAME",@"APPROVE_TYPE"];
        }
            break;
        case 2:
        {
            attendanceRecordsDC.tipTitleLabelArray = @[@"出差事由：",@"姓名：",@"职务：",@"科室：",@"出差地点：",@"会议培训期间费用支付单位：",@"出差时间：",@"出差时长：",@"乘坐交通工具(是否带车）：",@"抄送：",@"审批人：",@"备注：",@"审批状态："];
            attendanceRecordsDC.infoTitleLabelArray = @[@"APPROVE_MAIN",@"CREATE_NAME",@"TYPENAME",@"SYS_ORG_CODE",@"away",@"APPROVE_DEPART",@"BETWEEN_TIME",@"AWAY_DURATION",@"AWAY_TOOL",@"SEND_NAME",@"APPROVE_NAME",@"AWAY_REMARKS",@"APPROVE_TYPE"];
        }
            break;
        case 3:
        {
            attendanceRecordsDC.tipTitleLabelArray = @[@"用车事由：",@"姓名：",@"职务：",@"科室：",@"目的地：",@"用车人数：",@"车牌号：",@"出车公里数：",@"回车公里数：",@"用车公里数：",@"用车开始时间：",@"用车结束时间：",@"抄送：",@"审批人：",@"审批状态："];
            attendanceRecordsDC.infoTitleLabelArray = @[@"APPROVE_MAIN",@"CREATE_NAME",@"TYPENAME",@"SYS_ORG_CODE",@"CAR_OPTION",@"CAR_NUM",@"CAR_NUMBER",@"MILEAGE_OUT",@"RETURN_MILEAGE",@"USE_MILEAGE",@"START_TIME",@"END_TIME",@"SEND_NAME",@"APPROVE_NAME",@"APPROVE_TYPE"];
        }
            break;
        case 4:
        {
            [MBProgressHUD showTipMessageInWindow:@"记录已撤销"];
            return;
        }
            break;
        default:
        {
            [MBProgressHUD showTipMessageInWindow:@"状态错误"];
            return;
        }
            break;
    }
    [self.navigationController pushViewController:attendanceRecordsDC animated:true];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return LSLevinBookListViewCellHeight;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *sectionHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 8)];
    sectionHeaderView.backgroundColor = hexColor(eeeeee);
    return sectionHeaderView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 8;
}

- (NSMutableArray *)dataArrayM {
    if (!_dataArrayM) {
        _dataArrayM = [[NSMutableArray alloc] init];
    }
    return _dataArrayM;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, headerSearchViewHeight, ScreenWidth, ScreenHeight-SafeAreaTopHeight-headerSearchViewHeight)];
        _tableView.backgroundColor = hexColor(eeeeee);
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableFooterView = [UIView new];
        [_tableView registerClass:LSLevinBookListViewCell.class forCellReuseIdentifier:LSLevinBookListViewCellID];
    }
    return _tableView;
}

- (NZKNoDataView *)nodataView {
    if (!_nodataView) {
        _nodataView = [[NZKNoDataView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight-SafeAreaTopHeight-headerSearchViewHeight) withTip:@"暂无相关信息" andButtonText:nil];
    }
    return _nodataView;
}

- (NZKNetworkErrorView *)networkErrorView {
    if (!_networkErrorView) {
        WS
        _networkErrorView = [[NZKNetworkErrorView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight-SafeAreaTopHeight-headerSearchViewHeight) withRefreshBlock:^{
            [weakSelf loadData];
        }];
    }
    return _networkErrorView;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
